package cn.zkteco.doordu.utils;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2017/10/11.
 */

public class TransformUtil {

    private static String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};


    public static String byteArrayToString(byte[] results) {
        StringBuilder sb = new StringBuilder();
        for (byte result : results) {
            //per byte to string
            sb.append(byteToString(result));
        }
        return sb.toString();
    }

    public static Object byteToString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hex[d1] + hex[d2];
    }

    public static byte[] string2bytes(String key) {
        int len = key.length() / 2;
        byte[] key_b = new byte[len];
        String sub;
        for (int i = 0; i < len; i++) {
            sub = key.substring(2 * i, 2 + 2 * i);
            key_b[i] = (byte) Integer.parseInt(sub, 16);
        }
        return key_b;
    }

    public static String byteArrayToHex(byte[] byteArray) {

        // 首先初始化一个字符数组，用来存放每个16进制字符

        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};


        // new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））

        char[] resultCharArray = new char[byteArray.length * 2];


        // 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去

        int index = 0;

        for (byte b : byteArray) {

            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];

            resultCharArray[index++] = hexDigits[b & 0xf];

        }


        // 字符数组组合成字符串返回

        return new String(resultCharArray);
    }

    public static byte[] string2byteArr(String array) {
        int len = array.length() / 2;

        char[] cs = array.toCharArray();

        int charLen = 2 * len;

        if ((charLen & 0x01) != 0) {
            throw new RuntimeException("Odd number of characters.");
        }

        byte[] out = new byte[charLen >> 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; j < charLen; i++) {
            int f = toDigit(cs[j], j) << 4;
            j++;
            f = f | toDigit(cs[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }

    public static int toDigit(char ch, int index) {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new RuntimeException("Illegal hexadecimal character " + ch
                    + " at index " + index);
        }
        return digit;
    }

    public static byte[] getMD5(String key) {

        byte[] xKey = string2bytes(key);

        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("md5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] key_ble = messageDigest.digest(xKey);

        byte[] eight_key = new byte[8];

        System.arraycopy(key_ble, 4, eight_key, 0, eight_key.length);

        return eight_key;
    }


    /**
     * hex -> ascii
     * @param bytes
     * @return
     */
    public static String getChars (byte[] bytes) {
        Charset cs = Charset.forName ("UTF-8");
        ByteBuffer bb = ByteBuffer.allocate (bytes.length);
        bb.put (bytes);
        bb.flip ();
        CharBuffer cb = cs.decode (bb);
        return new String(cb.array());
    }


}


